#!/bin/bash
# ============================================
# Hive Docker 启动脚本
# 用途：使用 docker-compose 启动 Hive 服务
# ============================================

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

CONTAINER_NAME="hive_cmcc"

echo -e "${GREEN}============================================${NC}"
echo -e "${GREEN}Hive Docker 启动脚本${NC}"
echo -e "${GREEN}============================================${NC}"
echo ""

# 检查 Docker 是否运行
if ! docker info > /dev/null 2>&1; then
    echo -e "${RED}错误：Docker 未运行${NC}"
    echo "请先启动 Docker"
    exit 1
fi

# 检查 docker-compose 是否存在
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null 2>&1; then
    echo -e "${RED}错误：未找到 docker-compose 命令${NC}"
    exit 1
fi

# 使用 docker compose 或 docker-compose
COMPOSE_CMD="docker compose"
if ! docker compose version &> /dev/null 2>&1; then
    COMPOSE_CMD="docker-compose"
fi

# 检查容器是否存在
if docker ps -a --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    echo -e "${YELLOW}检测到容器 ${CONTAINER_NAME} 已存在${NC}"

    # 检查容器是否正在运行
    if docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
        echo "正在停止容器..."
        docker stop ${CONTAINER_NAME}
    fi

    echo "正在删除容器..."
    docker rm ${CONTAINER_NAME}
    echo -e "${GREEN}✓ 容器已删除${NC}"
    echo ""
fi

# 启动 Hive
echo "正在启动 Hive 容器..."
$COMPOSE_CMD up -d

# 检查启动状态
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Hive 容器启动成功！${NC}"
    echo ""
    echo "容器信息："
    docker ps --filter "name=${CONTAINER_NAME}" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
    echo ""
    echo "连接信息："
    echo "  HiveServer2: jdbc:hive2://localhost:10000"
    echo "  Web UI: http://localhost:10002"
    echo ""
    echo "查看日志："
    echo "  docker logs -f ${CONTAINER_NAME}"
    echo ""
    echo "停止容器："
    echo "  $COMPOSE_CMD down"
    echo ""
    echo -e "${GREEN}============================================${NC}"
else
    echo -e "${RED}✗ Hive 容器启动失败${NC}"
    echo "请检查 docker-compose.yml 配置"
    exit 1
fi
